<template>
  <div>
    <div class="app-container">
      <!--对象操作-->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Back" @click="handleBack">
            返回
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="ChatLineSquare"
            @click="handleComment"
            v-hasPermi="['tms:bug:comment']"
            >评论
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Connection"
            @click="handleAssociate"
            v-hasPermi="['tms:bug:associate']"
            >关联
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="Edit"
            @click="handleEdit"
            v-hasPermi="['tms:bug:edit']"
            >修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            @click="handleDelete"
            v-hasPermi="['tms:bug:delete']"
            >删除
          </el-button>
        </el-col>
        <y-history-toolbar
          :prefix="form.prefix"
          :historys="historys"
          :command="handleCommand"
        />
      </el-row>

      <!-- 信息展示 -->
      <el-row :gutter="10">
        <!-- 左侧详情展示 -->
        <el-col :lg="16" :xs="24">
          <!-- 描述卡片-->
          <el-card :loading="loadingDetails">
            <div class="card-header">
              <h4><strong>描述信息</strong></h4>
            </div>
            <div class="card-body">
              <div class="editor-content" v-html="form.description"></div>
            </div>
          </el-card>

          <!-- 备注卡片 -->
          <div v-if="form.remark">
            <br />
            <el-card>
              <div class="card-header">
                <h4><strong>备注信息</strong></h4>
              </div>
              <div class="card-body">
                <div v-html="form.remark"></div>
              </div>
            </el-card>
          </div>

          <!-- 修复卡片 -->
          <div :loading="loadingResolutions" v-if="resolutions.length > 0">
            <br />
            <el-card>
              <div class="card-header">
                <h4><strong>解决信息</strong></h4>
              </div>
              <div class="card-body">
                <div>
                  <el-timeline style="max-width: 1000px">
                    <el-timeline-item
                      v-for="(resolution, index) in resolutions"
                      :key="index"
                      :timestamp="
                        resolution.create_time +
                        ' ： ' +
                        resolution.creator_name +
                        '；   解决方案：' +
                        (resolution.extras?.resolved_type || '') +
                        '；   解决版本：' +
                        (resolution.extras?.resolved_version || '')
                      "
                      type="primary"
                      :hollow="true"
                      placement="top"
                      size="large"
                    >
                      <div
                        class="editor-content"
                        v-html="resolution.description"
                      ></div>
                    </el-timeline-item>
                  </el-timeline>
                </div>
              </div>
            </el-card>
          </div>

          <!-- 验证卡片 -->
          <div :loading="loadingVerifications" v-if="verifications.length > 0">
            <br />
            <el-card>
              <div class="card-header">
                <h4><strong>验证信息</strong></h4>
              </div>
              <div class="card-body">
                <div>
                  <el-timeline style="max-width: 1000px">
                    <el-timeline-item
                      v-for="(verification, index) in verifications"
                      :key="index"
                      :timestamp="
                        verification.create_time +
                        ' ： ' +
                        verification.creator_name +
                        '：   验证结论：' +
                        (verification.extras?.result || '')
                      "
                      type="primary"
                      :hollow="true"
                      placement="top"
                      size="large"
                    >
                      <div
                        class="editor-content"
                        v-html="verification.description"
                      ></div>
                    </el-timeline-item>
                  </el-timeline>
                </div>
              </div>
            </el-card>
          </div>

          <!-- 评论卡片 -->
          <div :loading="loadingComments" v-if="comments.length > 0">
            <br />
            <el-card>
              <div class="card-header">
                <h4><strong>评论信息</strong></h4>
              </div>
              <div class="card-body">
                <div>
                  <el-timeline style="max-width: 1000px">
                    <el-timeline-item
                      v-for="(comment, index) in comments"
                      :key="index"
                      :timestamp="
                        comment.create_time + ' ： ' + comment.creator_name
                      "
                      type="primary"
                      :hollow="true"
                      placement="top"
                      size="large"
                    >
                      <div
                        class="editor-content"
                        v-html="comment.content"
                      ></div>
                    </el-timeline-item>
                  </el-timeline>
                </div>
              </div>
            </el-card>
          </div>
        </el-col>

        <!-- 右侧属性展示 -->
        <el-col :lg="8" :xs="8">
          <el-card :loading="loadingDetails">
            <el-tabs v-model="activeName">
              <el-tab-pane label="基本信息" name="1">
                <el-descriptions direction="vertical" :column="1" border>
                  <el-descriptions-item label="缺陷编号">{{
                    form.number
                  }}</el-descriptions-item>
                  <el-descriptions-item label="缺陷名称">{{
                    form.name
                  }}</el-descriptions-item>
                  <el-descriptions-item label="所属产品">
                    <router-link
                      v-if="form.product"
                      :to="'/pms/product-info/index/' + form.product.value"
                      class="link-type"
                    >
                      <span>{{ form.product.label }}</span>
                    </router-link>
                  </el-descriptions-item>
                  <el-descriptions-item label="所属模块">
                    <router-link
                      v-if="form.module"
                      :to="'/pms/module-info/index/' + form.module.value"
                      class="link-type"
                    >
                      <span>{{ form.module.label }}</span>
                    </router-link>
                  </el-descriptions-item>
                  <el-descriptions-item label="影响版本">
                    <router-link
                      v-if="form.version"
                      :to="'/pms/version-info/index/' + form.version.value"
                      class="link-type"
                    >
                      <span>{{ form.version.label }}</span>
                    </router-link>
                  </el-descriptions-item>
                  <el-descriptions-item label="缺陷类型">
                    <y-dict-tag :options="tms_bug_type" :value="form.type" />
                  </el-descriptions-item>
                  <el-descriptions-item label="严重性">
                    <y-dict-tag
                      :options="sys_gravity_level"
                      :value="form.gravity"
                    />
                  </el-descriptions-item>
                  <el-descriptions-item label="优先级">
                    <y-dict-tag
                      :options="sys_priority_level"
                      :value="form.priority"
                    />
                  </el-descriptions-item>
                  <el-descriptions-item label="期望解决时间">{{
                    form.resolved_time_expected
                  }}</el-descriptions-item>
                  <el-descriptions-item label="开发接口人">{{
                    form.downer ? form.downer.label : ""
                  }}</el-descriptions-item>
                  <el-descriptions-item label="测试接口人">{{
                    form.towner ? form.towner.label : ""
                  }}</el-descriptions-item>
                  <el-descriptions-item label="创建人">{{
                    form.creator_name
                  }}</el-descriptions-item>
                  <el-descriptions-item label="创建时间">{{
                    form.create_time
                  }}</el-descriptions-item>
                  <el-descriptions-item label="状态">
                    <y-dict-tag
                      :options="tms_bug_status"
                      :value="form.status"
                    />
                  </el-descriptions-item>
                  <el-descriptions-item label="标签">
                    <y-tag v-model="form.tags" :editable="false" />
                  </el-descriptions-item>
                </el-descriptions>
              </el-tab-pane>
              <el-tab-pane label="相关信息" name="2">
                <el-descriptions direction="vertical" :column="1" border>
                  <el-descriptions-item label="关联需求">
                    <router-link
                      v-for="(item, index) in form.reqs"
                      :to="'/pms/requirement-info/index/' + item.id"
                      class="link-type"
                    >
                      <span>{{ index + 1 }}.{{ item.name }}</span>
                      <br />
                    </router-link>
                  </el-descriptions-item>
                  <el-descriptions-item label="关联用例">
                    <router-link
                      v-for="(item, index) in form.tcs"
                      :to="'/tms/testcase-info/index/' + item.value"
                      class="link-type"
                    >
                      <span>{{ index + 1 }}.{{ item.label }}</span>
                      <br />
                    </router-link>
                  </el-descriptions-item>
                  <el-descriptions-item label="关联缺陷">
                    <router-link
                      v-for="(item, index) in form.related_bugs"
                      :to="'/tms/bug-info/index/' + item.value"
                      class="link-type"
                    >
                      <span>{{ index + 1 }}.{{ item.label }}</span>
                      <br />
                    </router-link>
                  </el-descriptions-item>
                </el-descriptions>
              </el-tab-pane>
            </el-tabs>
          </el-card>
          <br />
          <el-card :loading="loadingOperateHistory">
            <div class="card-header">
              <h4><strong>操作记录</strong></h4>
            </div>
            <div class="card-body">
              <ul class="list">
                <li
                  v-for="(history, index) in operateHistorys"
                  :key="index"
                  class="history-item"
                >
                  <div
                    class="avatar"
                    style="width: 16px; height: 16px; font-size: 12px"
                  >
                    <span>{{ index + 1 }}</span>
                  </div>
                  <div class="content">
                    {{ history.create_time }}, 由
                    <strong>{{ history.creator_name }}</strong>
                    {{ getActionText(history.operation) }}
                    <!-- 如果操作为"UPDATE"、"ACTIVATE"、"SUSPEND"，且description不为空则显示 -->
                    <template
                      v-if="
                        ['UPDATE', 'ACTIVATE', 'SUSPEND'].includes(
                          history.operation
                        ) && history.description != ''
                      "
                    >
                      ，<strong>{{ history.description }}</strong> </template
                    >。
                  </div>
                </li>
              </ul>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 添加或修改对话框 -->
    <au-bug
      :id="id"
      v-model="open"
      :title="title"
      operate="update"
      :getMethod="getBug"
      :updateMethod="updateBug"
      @submited="submited"
      @close="open = false"
    >
    </au-bug>
    <au-comment
      :id="id"
      v-model="openBugComment"
      :title="title"
      operate="add"
      :getMethod="getBugComment"
      :addMethod="addBugComment"
      :updateMethod="updateBugComment"
      @submited="submited"
      @close="openBugComment = false"
    >
    </au-comment>

    <bug-associate
      :id="id"
      v-model="openBugAssociate"
      :title="title"
      @submited="submited"
      @close="openBugAssociate = false"
    >
    </bug-associate>
  </div>
</template>

<script setup name="BugInfo">
import { getBug, getHistory, updateBug, delBug } from "@/api/tms/bug";
import {
  getBugComment,
  addBugComment,
  updateBugComment,
} from "@/api/tms/bug/comment";
import { listBugComment } from "@/api/tms/bug/comment";
import { listBugOperate } from "@/api/tms/bug/operate";
import AuBug from "./components/AuBug";
import AuComment from "./components/AuComment";
import BugAssociate from "./components/BugAssociate";

const { proxy } = getCurrentInstance();
const { tms_bug_status, sys_priority_level, sys_gravity_level, tms_bug_type } =
  proxy.useDict(
    "tms_bug_status",
    "sys_priority_level",
    "sys_gravity_level",
    "tms_bug_type"
  );

const id = ref(null);
const open = ref(false);
const title = ref("");
const activeName = ref("1");
const historys = ref([]);
const comments = ref([]);
const resolutions = ref([]);
const verifications = ref([]);
const operateHistorys = ref([]);
const openBugComment = ref(false);
const openBugAssociate = ref(false);

const loadingDetails = ref(false);
const loadingResolutions = ref(false);
const loadingVerifications = ref(false);
const loadingComments = ref(false);
const loadingOperateHistory = ref(false);

const data = reactive({
  form: {},
});

const { form } = toRefs(data);

/** 获取缺陷详情 */
async function getInfo() {
  try {
    const id = proxy.$route.params.id;
    await Promise.all([
      loadBaseInfo(id),
      loadResolutions(id),
      loadVerifications(id),
      loadComments(id),
      loadOperateHistory(id),
      loadHistory(id),
    ]);
  } catch (error) {
    console.error("初始化数据失败:", error);
  }
}

// 获取基础信息（缺陷描述、备注、属性等）
async function loadBaseInfo(id) {
  try {
    loadingDetails.value = true;
    const res = await getBug(id);
    form.value = res.data;
  } catch (error) {
    console.error("加载基础信息失败:", error);
  } finally {
    loadingDetails.value = false;
  }
}

// 获取解决信息
async function loadResolutions(id) {
  try {
    loadingResolutions.value = true;
    const res = await listBugOperate({ bug: id, operation: "RESOLVE" });
    resolutions.value = res.data;
  } catch (error) {
    console.error("加载解决信息失败:", error);
  } finally {
    loadingResolutions.value = false;
  }
}

// 获取验证信息
async function loadVerifications(id) {
  try {
    loadingVerifications.value = true;
    const res = await listBugOperate({ bug: id, operation: "VERIFY" });
    verifications.value = res.data;
  } catch (error) {
    console.error("加载验证信息失败:", error);
  } finally {
    loadingVerifications.value = false;
  }
}

// 获取评论信息
async function loadComments(id) {
  try {
    loadingComments.value = true;
    const res = await listBugComment({ bug: id });
    comments.value = res.data;
  } catch (error) {
    console.error("加载评论信息失败:", error);
  } finally {
    loadingComments.value = false;
  }
}

// 获取历史记录
async function loadHistory(id) {
  try {
    const res = await getHistory(id);
    historys.value = res.data;
  } catch (error) {
    console.error("加载历史记录失败:", error);
  }
}

// 获取操作历史
async function loadOperateHistory(id) {
  try {
    loadingOperateHistory.value = true;
    const res = await listBugOperate({ bug: id });
    operateHistorys.value = res.data;
  } catch (error) {
    console.error("加载操作记录失败:", error);
  } finally {
    loadingOperateHistory.value = false;
  }
}

/** 查询某条历史记录 */
function handleCommand(command) {
  form.value = command;
}

/** 返回按钮操作 */
function handleBack() {
  proxy.$router.back();
}

/** 评论按钮操作 */
function handleComment() {
  id.value = form.value.id;
  openBugComment.value = true;
  title.value = "评论缺陷";
}

/** 关联按钮操作 */
function handleAssociate() {
  id.value = form.value.id;
  openBugAssociate.value = true;
  title.value = "关联缺陷";
}

/** 修改操作 */
function handleEdit() {
  id.value = form.value.id;
  open.value = true;
  title.value = "修改缺陷";
}

/** 删除按钮操作 */
function handleDelete() {
  proxy.$modal
    .confirm('是否确认删除缺陷编号为"' + form.value.number + '"的数据项?')
    .then(() => {
      return delBug(form.value.id);
    })
    .then(() => {
      proxy.$modal.msgSuccess("删除成功");
      handleBack();
    })
    .catch(() => {});
}

function getActionText(action) {
  const actions = {
    CREATE: "创建",
    UPDATE: "更新",
    ACTIVATE: "激活",
    RESOLVE: "解决",
    VERIFY: "验证",
    SUSPEND: "挂起",
  };
  return actions[action] || action;
}

/** 添加/修改对象后触发事件 */
async function submited() {
  await getInfo();
}

onMounted(async () => {
  await getInfo();
});
</script>

<style>
/* 调整编辑器中的视频大小 */
.editor-content video {
  width: 100%;
  height: auto;
}

/* 调整编辑器中的图片大小 */
.editor-content img {
  width: 100%;
  height: auto;
}

.list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.history-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.avatar {
  background-color: #f0f0f0;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 12px;
}

.content {
  flex: 1;
}
</style>
